package com.camtc.camcenter.service.impl;

import com.camtc.camcenter.base.service.impl.BaseServiceImpl;
import com.camtc.camcenter.dao.entity.CloudPermission;
import com.camtc.camcenter.dao.repository.CloudRoleRepository;
import com.camtc.camcenter.dao.repository.CloudUserRepository;
import com.camtc.camcenter.dao.entity.CloudUser;
import com.camtc.camcenter.service.CloudUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * @date
 */

@Service
@Transactional(readOnly = true)
public class CloudUserServiceImpl extends BaseServiceImpl<CloudUser> implements CloudUserService {

    private CloudUserRepository cloudUserRepository;

    @Override
    public void initJpaRepository() {
        this.jpaRepository = cloudUserRepository;
    }

    @Autowired
    public void setCloudUserRepository(CloudUserRepository cloudUserRepository) {
        this.cloudUserRepository = cloudUserRepository;
    }

    @Override
    public CloudUser findByUsername(String username) {
        return cloudUserRepository.findCloudUserByUserName(username);
    }

    @Override
    public List<String> findPermissions(String username) {
        List<String> permissions = new ArrayList<>();
        CloudUser user = findByUsername(username);
        if (user != null) {
            if (user.getRoles().size() > 0) {
                permissions = user.getRoles().stream().flatMap(
                        cloudRole -> cloudRole.getPermissions().stream().map(CloudPermission::getPermissionCode)).collect(Collectors.toList());
            }
        }
        return permissions;
    }
}
